package com.atgouwu.mall.seckill.scheduled;

import com.atgouwu.mall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架
 */
@Slf4j
@Service
public class SeckillScheduled {

    @Autowired
    private RedissonClient redissonClient;
    private final String upload_lock = "seckill:upload:lock"; //秒杀商品上架功能的锁
    @Autowired
    private SeckillService seckillService;

    //每天晚上3点,上架最近三天需要秒杀的商品,重复上架无需处理
    @Scheduled(cron = "0 0 1/1 * * ? ")
    public void uploadSeckillSkuLatest3Days() {
        RLock lock = redissonClient.getLock(upload_lock); //分布式锁(幂等性)
        try {
            lock.lock(10, TimeUnit.SECONDS); //加锁10秒
            seckillService.uploadSeckillSkuLatest3Days(); //上架三天需要秒杀的商品
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
